import { useState, useEffect, useMemo } from 'react';
import { formatTime } from '@/utils';

const useTimeStr = () => {
  const [time, setTime] = useState<number>(0);
  useEffect(() => {
    setTime(new Date().getTime());

    const timer = setInterval(() => {
      setTime(new Date().getTime());
    }, 1000);

    // 组件卸载的时候，需要去清除定时器
    return () => {
      clearInterval(timer);
    };
  }, []);

  const timeStr = useMemo(() => {
    return formatTime(time, 's');
  }, [time]);

  return timeStr;
};

export default useTimeStr;
